/*
http://www.ay1.cc/article/29900.html
*/

export default {
  isOnline() {
    // 是否连网
    return navigator.onLine;
  },
  getUa() {
    return window.navigator.userAgent.toLowerCase();
  },
  getEnv() {
    // 获取运行环境
    const ua = this.getUa();
    return {
      isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        ua
      ),
      isWx: ua.match(/MicroMessenger/i) == "micromessenger",
      isIpad: ua.indexOf("ipad") > -1,
      isIphone: ua.indexOf("iphone os") > -1,
      isUc: ua.indexOf("ucweb") > -1,
      isWindows: ua.indexOf("windows") > -1,
      isAndroid: ua.indexOf("android") > -1 || ua.indexOf("adr") > -1,
      isIos: /(iphone|ipod|ipad|ios)/i.test(ua),
      isQq: ua.indexOf("mqqbrowser") > -1 && ua.indexOf(" qq") < 0,
      // 是否qq内置浏览器
      isQQInstalled: ua.indexOf(" qq") > -1 && ua.indexOf("mqqbrowser") < 0
    };
  },
  setCookie(key, value, expire) {
    const d = new Date();
    d.setDate(d.getDate() + expire);
    document.cookie = `${key}=${value};expires=${d.toUTCString()}`;
  },
  getCookie(key) {
    const cookieStr = unescape(document.cookie);
    const arr = cookieStr.split("; ");
    let cookieValue = "";
    for (let i = 0; i < arr.length; i++) {
      const temp = arr[i].split("=");
      if (temp[0] === key) {
        cookieValue = temp[1];
        break;
      }
    }
    return cookieValue;
  },
  createElement(str) {
    // 创建元素  createElement(`<p class="p"> </p>`)
    const el = document.createElement("div");
    el.innerHTML = str;
    return el.firstElementChild;
  },
  timeTaken(callback) {
    // 测量函数执行时间 timeTaken(() => Math.pow(2, 10));
    console.time("timeTaken");
    const r = callback();
    console.timeEnd("timeTaken");
    return r;
  },
  setStyle(el, ruleName, val) {
    // setStyle(document.querySelector('p'), 'font-size', '20px');
    el.style[ruleName] = val;
  },
  scrollToTop() {
    // 返回顶部
    const height =
      document.documentElement.scrollTop || document.body.scrollTop;
    if (height > 0) {
      window.requestAnimationFrame(scrollToTop);
      window.scrollTo(0, height - height / 8);
    }
  },
  smoothScroll(selector) {
    // 滚动到元素
    document.querySelector(selector).scrollIntoView({
      behavior: "smooth"
    });
  },
  loadFile(url, flag) {
    // 动态加文件
    // jquery 则 $('head').append($('<>直接写标签元素<>'))
    const el = document.createElement(flag ? "link" : "script");
    el.type = flag ? "text/css" : "text/javascript";
    el.href = url;
    document.getElementsByTagName("head")[0].appendChild(el);
  }
};
